import 'package:flutter/material.dart';
class WrapFlowRoute extends StatefulWidget {
  const WrapFlowRoute({Key? key}) : super(key: key);

  @override
  _WrapFlowRouteState createState() => _WrapFlowRouteState();
}

class _WrapFlowRouteState extends State<WrapFlowRoute> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('wrap_flow布局'),
      ),
      body: Column(
        children: [buildWrap(), buildFlow()],
      ),
    );
  }

  Widget buildWrap() {
    return const Wrap(
      spacing: 10,//子元素水平margin
      runSpacing: 4,//子元素垂直margin
      alignment: WrapAlignment.center,//主轴方向居中
      children: [
        Chip(
            avatar: CircleAvatar(
              backgroundColor: Colors.blue,
              child: Text('H'),
            ),
            label: Text('hamlidfs')),
        Chip(
            avatar: CircleAvatar(
              backgroundColor: Colors.green,
              child: Text('B'),
            ),
            label: Text('bnana')),
        Chip(
            avatar: CircleAvatar(
              backgroundColor: Colors.black,
              child: Text('C'),
            ),
            label: Text('cat')),
      ],
    );
  }

  Widget buildFlow() {
    return Flow(
      delegate: TestFlowDelegate(margin: const EdgeInsets.all(10)),
      children: [
        Container(width: 80, height: 80, color: Colors.red),
        Container(width: 80, height: 80, color: Colors.blue),
        Container(width: 80, height: 80, color: Colors.green),
      ],
    );
  }
}

class TestFlowDelegate extends FlowDelegate {
  EdgeInsets margin;
  TestFlowDelegate({this.margin = EdgeInsets.zero});
  double width = 0;
  double height = 0;
  @override
  void paintChildren(FlowPaintingContext context) {
    var x = margin.left;
    var y = margin.top;
    for (int i = 0; i < context.childCount; i++) {
      var w = context.getChildSize(i)!.width + x + margin.right;
      if (w < context.size.width) {
        context.paintChild(i, transform: Matrix4.translationValues(x, y, 0.0));
        x = w + margin.left;
      } else {
        x = margin.left;
        y += context.getChildSize(i)!.height + margin.top + margin.bottom;
        //绘制子widget(有优化)
        context.paintChild(i, transform: Matrix4.translationValues(x, y, 0.0));
        x += context.getChildSize(i)!.width + margin.left + margin.right;
      }
    }
  }
  @override 
  Size getSize(BoxConstraints constraints){
    return const Size(double.infinity,200.0);
  }
  @override 
  bool shouldRepaint(FlowDelegate oldDelegate){
    return oldDelegate != this;
  }
}
